﻿//////////////////////////////////////////////////////////////////////////////
//                                                                          //
// Copyright 2010 ZGDev Software                                            //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//   http://www.apache.org/licenses/LICENSE-2.0                             //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
//                                                                          //
//////////////////////////////////////////////////////////////////////////////

using System;
using System.Threading;

namespace ZGDev.FormSpark
{
    /// <summary>
    /// Internal utility class used for simplifying dispatching work items to the .NET thread pool.
    /// This can clean up our code since we can use Lamda expressions, allowing us to have a way
    /// to write small clean work items.
    /// </summary>
    internal static class Dispatch
    {
        /// <summary>
        /// The main thread dispatcher for this application.
        /// </summary>
        /// <seealso cref="IMainThreadDispatcher"/>
        internal static IMainThreadDispatcher MainThreadDispatcher;

        /// <summary>
        /// Delegate describing our "work items." They take no arguments and return nothing.
        /// </summary>
        public delegate void DispatchTaskDelegate();

        /// <summary>
        /// Dispatches a work item to the thread pool.
        /// </summary>
        /// <param name="del">The work item to dispatch.</param>
        public static void Run(DispatchTaskDelegate del)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(runTask), del);
        }

        /// <summary>
        /// Called by the thread pool to actually run the work item.
        /// </summary>
        /// <param name="arg">The work item to run.</param>
        private static void runTask(object arg)
        {
            DispatchTaskDelegate del = (DispatchTaskDelegate)arg;
            del();
        }
    }
}
